<template>
  <div class="playbox-container">
    <!-- 封面 -->
    <img :src="picUrl" alt="" v-show="picUrl !== null" @click="goSong" />
    <!-- 歌曲名称 -->
    <div class="name" v-if="picUrl !== null">
      <span>{{ songDetail.name }}</span>
      <span v-if="songDetail.alia.length !== 0">（{{ songDetail.alia[0] }}）</span>
    </div>
    <!-- 喜欢 -->
    <i class="el-icon-star-on" v-show="songId !== ''" :class="isLoved()" @click="myLove"></i>
    <!-- 播放 -->
    <i
      class="el-icon-caret-right"
      v-show="songUrl !== null"
      @click="
        audioPlay()
        changeAudioState(state)
      "
    ></i>
    <audio ref="audioRef" :src="songUrl" autobuffer></audio>
    <div class="control-box">
      <el-slider v-model="getProgressBar" :show-tooltip="false" @change="ctChange"></el-slider>
      <span class="now">{{ (ct * 1000) | conversion('mm : ss') }}</span>
      <span class="complete">{{ audioTime | conversion('mm : ss') }}</span>
    </div>
    <!-- 音量 -->
    <div class="volume" @mouseover="showV" @mouseout="hideV">
      <i></i>
      <el-slider ref="esRef" style="display: none" v-model="volume" :show-tooltip="false" vertical height="80px" @change="vChange"></el-slider>
      <span></span>
    </div>
    <!-- 播放列表 -->
    <div class="playListBox">
      <i title="打开播放列表" @click="showPlayList"></i>
      <div class="playList" v-show="showPlayListState">
        <div class="playListTitle">
          <h2>播放列表({{ playList.length }})</h2>
          <h4 @click="clearList">清空列表</h4>
        </div>
        <el-table :data="playList" stripe style="width: 100%" :show-header="false" :height="tableHeight">
          <el-table-column prop="name" min-width="50%" show-overflow-tooltip>
            <template slot-scope="scope">
              <span @click="chooseSong(scope.row.id)">{{ scope.row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="artist" min-width="20%" show-overflow-tooltip> </el-table-column>
          <el-table-column prop="time" min-width="20%">
            <template slot-scope="scope">{{ scope.row.time | conversion('mm : ss') }}</template>
          </el-table-column>
          <el-table-column prop="delete" min-width="10%">
            <template slot-scope="scope">
              <div class="el-icon-delete" style="font-size: 16px; cursor: pointer" @click="deletePlayList(scope.row)"></div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>

<script>
import bus from '@/components/eventBus.js'
import { mapGetters, mapMutations } from 'vuex'
import { savePlayList, loadPlayList, deletePlayList, clearPlayList, saveLastPlayList, loadLastPlayList, saveMyLoveSongList, loadMyLoveSongList, deleteMyLoveSongList } from '@/js/cache'
// 获取歌曲详情
import { getSongByIdAPI } from '@/api/Song.js'
// 获取歌曲url
import { getSongUrlByIdAPI } from '@/api/playListAPI.js'
import state from '@/store/state'

export default {
  name: 'PlayBox',
  data() {
    return {
      songId: '',
      songDetail: {},
      picUrl: null,
      songUrl: null,
      // 音频时长
      audioTime: 0,
      // 当前播放时间
      // nowTime: 0,
      progressBar: 0,
      ct: 0,
      // 定时器
      timer: null,
      // 音频播放状态,默认暂停
      state: true,
      // 音量(0~100)
      volume: 100,
      // 播放列表
      playList: [],
      // el-table 高度
      tableHeight: 0,
      showPlayListState: false,
      myLoveSongList: []
    }
  },
  created() {
    bus.$on('songId', (val) => {
      this.songId = val
    })
    bus.$on('initPlayList', () => {
      this.playList = loadPlayList()
    })
    bus.$on('initLoveState', () => {
      this.myLoveSongList = loadMyLoveSongList()
    })
    this.getTableHeight()
  },
  mounted() {
    this.playList = loadPlayList()
    this.myLoveSongList = loadMyLoveSongList()
    //浏览器窗口大小变化时触发，重置 el-table 的高度
    window.onresize = () => {
      if (this.resizeFlag) {
        clearTimeout(this.resizeFlag)
      }
      this.resizeFlag = setTimeout(() => {
        this.getTableHeight()
        this.resizeFlag = null
      }, 100)
    }
  },
  computed: {
    // 计算进度条的进度
    getProgressBar: {
      get() {
        return ((this.ct * 1000) / this.audioTime) * 100
      },
      set(val) {
        this.progressBar = val
      }
    },
    ...mapGetters(['audioState'])
  },
  methods: {
    // 获取歌曲详情
    async getSong(ids) {
      // 歌曲详情
      const {
        data: { songs: res }
      } = await getSongByIdAPI(ids)
      this.songDetail = res[0]
      this.picUrl = this.songDetail.al.picUrl
      this.audioTime = this.songDetail.dt
      // console.log(res[0])
      // // 歌曲封面
      // this.picUrl = this.songDetail.al.picUrl
      // // 歌词
      // const {
      //   data: {
      //     lrc: { lyric: lyrStr }
      //   }
      // } = await getLyricByIdAPI(this.id)
      // this.lyric = lyrStr
      // // 初始化拆分歌词
      // this.lyrReady = this.formatLyric(this.lyric)
      // // 目前歌词，默认 0 秒时
      // this.nowLyr = this.lyrReady[0]

      // 定义对象，本地存储到播放列表中
      let songItem = {
        id: this.songId,
        name: this.songDetail.name,
        artist: this.songDetail.ar[0].name,
        time: this.songDetail.dt
      }
      // 播放列表
      savePlayList(songItem)
      this.playList = loadPlayList()
      // 最近播放
      let lastPlayItem = {
        id: this.songId,
        name: this.songDetail.name,
        artist: this.songDetail.ar[0].name,
        time: this.songDetail.dt,
        playTime: Date.parse(new Date())
      }
      saveLastPlayList(lastPlayItem)
    },
    // 获取音乐 url
    async getSongUrl(id) {
      const {
        data: {
          data: { [0]: res }
        }
      } = await getSongUrlByIdAPI(id)
      if (res.url !== null) {
        this.songUrl = res.url
      } else {
        alert('获取音乐失败')
      }
    },
    audioPlay() {
      if (this.timer) {
        clearInterval(this.timer)
      }
      if (this.$refs.audioRef.paused) {
        this.$refs.audioRef.play()
        // 定时器实时显示当前播放时间
        this.timer = window.setInterval(() => {
          // this.nowTime = this.nowTime + 1000
          // if (this.nowTime >= this.audioTime) {
          //   this.nowTime = this.audioTime
          //   clearInterval(this.timer)
          // }
          this.ct = this.$refs.audioRef.currentTime
          if (this.$refs.audioRef.ended) {
            clearInterval(this.timer)
          }
        }, 200)
      } else {
        this.$refs.audioRef.pause()
        // 清除定时器
        clearInterval(this.timer)
      }
      // 记录音频播放状态
      this.state = this.$refs.audioRef.paused
    },
    // 通过进度条滑块跳转播放位置
    ctChange() {
      this.$refs.audioRef.currentTime = ((this.progressBar / 100) * this.audioTime) / 1000
    },
    // 显示音量调节
    showV() {
      this.$refs.esRef.$el.style.display = 'block'
    },
    // 隐藏音量调节
    hideV() {
      this.$refs.esRef.$el.style.display = 'none'
    },
    // 设置音量值
    vChange() {
      this.$refs.audioRef.volume = this.volume / 100
    },

    // 路由跳转到对应的歌曲页面
    goSong() {
      this.$router.push({
        path: '/song',
        query: {
          id: this.songId
        }
      })
    },
    ...mapMutations({
      changeAudioState: 'CHANGE_AUDIO_STATE'
    }),
    getTableHeight() {
      this.tableHeight = window.innerHeight - 59 - 60 - 26.4 - 40
    },
    showPlayList() {
      this.showPlayListState = !this.showPlayListState
    },
    deletePlayList(item) {
      deletePlayList(item)
      this.playList = loadPlayList()
    },
    chooseSong(id) {
      this.songId = id
    },
    clearList() {
      clearPlayList()
      this.playList = loadPlayList()
    },
    sendSongId() {
      bus.$emit('songId', this.songId)
    },
    myLove() {
      console.log(this.myLoveSongList)
      // 判断是否存在
      const index = this.myLoveSongList.findIndex((item) => {
        return item.id === this.songDetail.id
      })
      if (index >= 0) {
        // 已存在,删除
        deleteMyLoveSongList(this.songDetail)
      } else {
        // 不存在，添加
        let obj = {
          id: this.songDetail.id,
          name: this.songDetail.name,
          artist: this.songDetail.ar,
          album: this.songDetail.al,
          time: this.songDetail.dt
        }
        saveMyLoveSongList(obj)
      }
      this.myLoveSongList = loadMyLoveSongList()
      // 重新渲染 class
      bus.$emit('initLoveState')
    },
    // 判断歌曲是否已喜欢，动态添加 class
    isLoved() {
      const index = this.myLoveSongList.findIndex((item) => {
        return item.id === this.songDetail.id
      })
      if (index >= 0) {
        return 'loved'
      }
    }
  },
  watch: {
    songId() {
      this.songUrl = null
      this.getSong(this.songId)
      this.getSongUrl(this.songId)
      this.sendSongId()
    },
    songUrl() {
      // 歌曲 url 变化后，即切换当前播放歌曲后
      // 重置当前播放时间
      this.ct = 0
      // 播放状态暂停
      // this.audioState = false
      // 清除定时器
      if (this.timer) {
        clearInterval(this.timer)
      }
    }
  }
}
</script>

<style lang="less" scoped>
.playbox-container {
  position: fixed;
  z-index: 10;
  bottom: 0;
  width: 100%;
  height: 59px;
  border-top: 1px solid #e1e1e1;
  background-color: #fff;
  img {
    position: absolute;
    top: 50%;
    margin-top: -23.75px;
    left: 10px;
    width: 47.5px;
    height: 47.5px;
    border-radius: 5px;
    cursor: pointer;
  }
  .name {
    position: absolute;
    top: 5px;
    left: 70px;
    width: 150px;
    font-size: 16px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    color: #9f9fbf;
    span {
      &:nth-child(1) {
        color: #373737;
      }
    }
  }
  .el-icon-star-on {
    position: absolute;
    top: 50%;
    margin-top: -12px;
    left: 15%;
    font-size: 24px;
    color: #e5e5e5;
    cursor: pointer;
  }
  .loved {
    color: #ec4141;
  }
  .el-icon-caret-right {
    position: absolute;
    top: 50%;
    margin-top: -14px;
    left: 20%;
    font-size: 28px;
    color: #313131;
    background-color: #f4f4f4;
    border-radius: 14px;
    cursor: pointer;
    &:hover {
      background-color: #e5e5e5;
    }
  }
  .control-box {
    margin: 0 auto;
    width: 30%;
    position: relative;
    .el-slider {
      /deep/.el-slider__runway {
        margin: 27px 0;
        .el-slider__bar {
          background-color: #ec4141;
        }
        .el-slider__button-wrapper {
          .el-slider__button {
            width: 12px;
            height: 12px;
            border: none;
            background-color: #ec4141;
            &.dragging,
            &.hover,
            &:hover {
              transform: scale(1);
            }
          }
        }
      }
    }
    .now {
      position: absolute;
      top: 16px;
      left: -60px;
    }
    .complete {
      position: absolute;
      top: 16px;
      right: -60px;
    }
  }
  // 音量调节部分
  .volume {
    position: absolute;
    top: 50%;
    margin-top: -11px;
    right: 20%;
    width: 22px;
    height: 22px;
    i {
      display: block;
      width: 22px;
      height: 22px;
      background: url('@/components/PlayBox/img/volume-icon.png') no-repeat;
      background-size: 100%;
      cursor: pointer;
    }
    .el-slider {
      position: absolute;
      bottom: 30px;
      background-color: #fff;
      border-radius: 3px;
      box-shadow: 0 0 6px -2px rgba(0, 0, 0, 0.6);
      /deep/.el-slider__runway {
        margin: 12px 8px;
        .el-slider__bar {
          background-color: #ec4141;
        }
        .el-slider__button-wrapper {
          left: -8px;
          width: 22px;
          height: 22px;
          .el-slider__button {
            width: 12px;
            height: 12px;
            border: none;
            background-color: #ec4141;
            &.dragging,
            &.hover,
            &:hover {
              transform: scale(1);
            }
          }
        }
      }
    }
    span {
      position: absolute;
      top: -8px;
      left: 50%;
      margin-left: -5px;
      width: 0;
      height: 0;
      line-height: 0;
      font-size: 0;
      border: 5px solid transparent;
      border-top-color: #fff;
    }
  }
  .playListBox {
    position: absolute;
    top: 50%;
    margin-top: -11px;
    right: 10%;
    width: 22px;
    height: 22px;
    i {
      display: block;
      width: 22px;
      height: 22px;
      background: url('@/components/PlayBox/img/play-list.png') no-repeat;
      background-size: 100%;
      cursor: pointer;
    }
    .playList {
      position: fixed;
      top: 59px;
      bottom: 60px;
      right: 0;
      width: 415px;
      background-color: #fff;
      box-shadow: -6px 0 10px -10px rgba(0, 0, 0, 0.6);
      .playListTitle {
        overflow: hidden;
        h2 {
          float: left;
          margin: 20px;
          font-size: 20px;
          color: #333;
        }
        h4 {
          float: right;
          margin: 23.6px 20px;
          font-size: 14px;
          font-weight: 400;
          color: #507daf;
          cursor: pointer;
          &:hover {
            color: #0b58b0;
          }
        }
      }
      /deep/.el-table {
        .el-table__body-wrapper {
          /*滚动条*/
          &::-webkit-scrollbar {
            width: 5px;
          }

          /*滑块部分*/
          &::-webkit-scrollbar-thumb {
            background-color: #ccc9cd;
            border-radius: 2.5px;
          }
          .el-table__body {
            width: 410px !important;
            .el-table__cell {
              padding: 9px 0;
              font-size: 12px;
            }
          }
        }
      }
    }
  }
}
</style>
